/*
 * @Description: 流程管理上下文
 * @Author: Rfan
 * @Date: 2022-12-11 11:27:10
 * @LastEditTime: 2023-01-12 14:41:26
 */

import { Context, createContext, FC, Key, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  addFlowItem,
  deleteFlowItem,
  deployProcessApi,
  editFlowItem,
  fetchFlowList,
  fetchProcessType,
  IEditFlowItemParams,
  IProcessTypeResponse,
  ISaveFlowDiagramParams,
  saveFlowDiagram
} from '@/api/workFlow/mgt';
import { FlowMgtReducer } from '../reducers/FlowMgtReducer';
import {
  DELETE_FLOW_ITEM,
  ADD_FLOW_ITEM,
  SET_FLOW_LIST,
  EDIT_FLOW_ITEM,
  SET_PROCESS_TYPE
} from '../constants';
import { SET_SELECTED_ITEM } from '@/view/accession/BatchManage/constants';
import type { IBaseDic, IPageQuery } from '@/interfaces/global';
import type { IAddFlowItemParams } from '@/api/workFlow/mgt';

// 初始化数据类型
export interface IInitialState {
  // 选中的表格条目
  selectItems: number[];

  // 回收站列表
  list: any[];
  levelList: IBaseDic[];

  processTypeList: IProcessTypeResponse[];
  processTypeFlatList: IProcessTypeResponse[];
}

// 初始化数据
const initialState: IInitialState = {
  selectItems: [],
  list: [],
  levelList: [
    { id: 0, name: '电子文件级' },
    { id: 1, name: '文件级' },
    { id: 2, name: '案卷级' },
    { id: 3, name: '项目级' }
  ],

  // 流程类型
  processTypeList: [],
  processTypeFlatList: []
};

// 生成context
const FlowMgtContext = createContext<IInitialState>(initialState);

export interface IActions {
  setSelectKey: (selectArr: number[]) => void;
  getFlowList: (params: any) => Promise<any>;
  addFlowItemFunc: (params: IAddFlowItemParams) => Promise<any>;
  editFlowItemFunc: (params: IEditFlowItemParams) => Promise<any>;
  saveFlowDiagramFunc: (params: ISaveFlowDiagramParams) => Promise<any>;
  delFlowItemFunc: (ids: Key[], content?: string) => void;
  deployProcessFunc: (id: Key) => void;
  getPrecessType: () => void;
}

export interface IFilters {
  precessTypeFilter: (id: string) => string;
}

// provider高阶组件
const FlowMgtContextProvider: FC = (props) => {
  const [state, dispatch] = useReducer(FlowMgtReducer, initialState);

  const actions: IActions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {number[]} selectArr
     */
    setSelectKey(selectArr: number[]) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取流程列表
     */
    getFlowList(params: IPageQuery) {
      return new Promise((resolve, reject) => {
        fetchFlowList(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_FLOW_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 增加流程
     * @param {IAddFlowItemParams} params
     * @return {Promise<any>}
     */
    addFlowItemFunc(params: IAddFlowItemParams): Promise<any> {
      return new Promise((resolve, reject) => {
        addFlowItem(params)
          .then((res) => {
            const data = res.data;
            dispatch({ type: ADD_FLOW_ITEM, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 编辑流程
     * @param {IEditFlowItemParams} params
     * @return {Promise<any>}
     */
    editFlowItemFunc(params: IEditFlowItemParams): Promise<any> {
      return new Promise((resolve, reject) => {
        editFlowItem(params)
          .then((res) => {
            const data = res.data;
            dispatch({ type: EDIT_FLOW_ITEM, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 更新流程图
     * @param {ISaveFlowDiagramParams} params
     * @return {Promise<any>}
     */
    saveFlowDiagramFunc(params: ISaveFlowDiagramParams): Promise<any> {
      return new Promise((resolve, reject) => {
        saveFlowDiagram(params)
          .then((res) => {
            message.success('保存成功');
            const data = res.data;
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 删除流程
     * @param {number[]} ids 删除条目的ID
     * @param {string} content 弹窗title
     */
    delFlowItemFunc(ids: Key[], content: string = '是否确认删除？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          deleteFlowItem(ids).then((res) => {
            const data = res.data;
            dispatch({ type: DELETE_FLOW_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    getPrecessType() {
      fetchProcessType().then((res) => {
        const data = res.data;
        dispatch({ type: SET_PROCESS_TYPE, data });
      });
    },

    deployProcessFunc(id: Key) {
      deployProcessApi(id).then(() => {
        message.success('部署成功');
      });
    }
  };

  const filters: IFilters = {
    precessTypeFilter(type) {
      return (
        state.processTypeFlatList.find((processType) => processType.flowType === type)?.name || '-'
      );
    }
  };

  useEffect(() => {
    actions.getPrecessType();
  }, []);

  return (
    <FlowMgtContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </FlowMgtContext.Provider>
  );
};

export type IContextValue = IInitialState & IActions & IFilters;
export const useFlowMgtContext = () => {
  return useContext(FlowMgtContext as Context<IContextValue>);
};

export { FlowMgtContext, FlowMgtContextProvider };
